// 餐品控制器
import Food from './FoodModel.js';
import FoodCategory from '../FoodCategory/FoodCategoryModel.js';
import { asyncHandler, ApiError } from '../../middleware/errorHandler.js';
import UploadService from '../../config/Upload.js';

export const FoodController = {
    /**
     * 创建餐品
     */
    create: asyncHandler(async (req, res) => {
        const { name, price, description, category_id, status, stock } = req.body;
        
        if (!name || !price || !category_id) {
            throw ApiError.badRequest('餐品名称、价格和分类不能为空');
        }
        
        // 检查分类是否存在
        const category = await FoodCategory.findByPk(category_id);
        if (!category) {
            throw ApiError.notFound('所选分类不存在');
        }
        
        const food = await Food.create({
            name,
            price,
            description,
            category_id,
            status,
            stock
        });
        
        return res.status(201).json({
            success: true,
            message: '餐品创建成功',
            data: food
        });
    }),

    /**
     * 获取所有餐品
     */
    getAll: asyncHandler(async (req, res) => {
        const { category_id, status } = req.query;
        const where = {};
        
        if (category_id) {
            where.category_id = category_id;
        }
        if (status) {
            where.status = status;
        }
        
        const foods = await Food.findAll({
            where,
            include: [{
                model: FoodCategory,
                as: 'category',
                attributes: ['id', 'name']
            }],
            order: [['id', 'ASC']]
        });
        
        return res.json({
            success: true,
            data: foods
        });
    }),

    /**
     * 获取单个餐品
     */
    getOne: asyncHandler(async (req, res) => {
        const { id } = req.params;
        
        const food = await Food.findByPk(id, {
            include: [{
                model: FoodCategory,
                as: 'category',
                attributes: ['id', 'name']
            }]
        });
        
        if (!food) {
            throw ApiError.notFound('餐品不存在');
        }
        
        return res.json({
            success: true,
            data: food
        });
    }),

    /**
     * 更新餐品信息
     */
    update: asyncHandler(async (req, res) => {
        const { id } = req.params;
        const { name, price, description, category_id, status, stock } = req.body;
        
        const food = await Food.findByPk(id);
        if (!food) {
            throw ApiError.notFound('餐品不存在');
        }
        
        // 如果更新分类，检查新分类是否存在
        if (category_id && category_id !== food.category_id) {
            const category = await FoodCategory.findByPk(category_id);
            if (!category) {
                throw ApiError.notFound('所选分类不存在');
            }
        }
        
        await food.update({
            name: name || food.name,
            price: price !== undefined ? price : food.price,
            description: description !== undefined ? description : food.description,
            category_id: category_id || food.category_id,
            status: status || food.status,
            stock: stock !== undefined ? stock : food.stock
        });
        
        return res.json({
            success: true,
            message: '餐品更新成功',
            data: food
        });
    }),

    /**
     * 更新餐品图片
     */
    updateImage: asyncHandler(async (req, res, next) => {
        const { id } = req.params;
        
        const food = await Food.findByPk(id);
        if (!food) {
            throw ApiError.notFound('餐品不存在');
        }
        
        // 使用上传服务处理图片上传
        UploadService.imageUploader(req, res, async (err) => {
            if (err) {
                return next(err instanceof ApiError ? err : new ApiError(400, `图片上传失败: ${err.message}`));
            }
            
            if (!req.files || req.files.length === 0) {
                return next(new ApiError(400, '没有上传图片文件'));
            }
            
            // 获取上传的图片URL
            const imageFile = req.files[0];
            const imageUrl = `/${imageFile.destination}/${imageFile.filename}`;
            
            // 更新餐品图片
            await food.update({ image: imageUrl });
            
            return res.json({
                success: true,
                message: '餐品图片更新成功',
                data: {
                    image: food.image
                }
            });
        });
    }),

    /**
     * 删除餐品
     */
    delete: asyncHandler(async (req, res) => {
        const { id } = req.params;
        
        const food = await Food.findByPk(id);
        if (!food) {
            throw ApiError.notFound('餐品不存在');
        }
        
        await food.destroy();
        
        return res.json({
            success: true,
            message: '餐品删除成功'
        });
    })
};